﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics.Contracts;
using ServiceManager.Utils;
namespace QuotationService.RealtimeQuotation
{
    class TickInfoRepository<TTickInfo, TTickInfoEntity>
        where TTickInfo : Quotation.TickInfoBase
        where TTickInfoEntity : struct
    {
        protected IEntityConverter<TTickInfo, TTickInfoEntity> converter;
        public TickInfoRepository(IEntityConverter<TTickInfo, TTickInfoEntity> converter)
        {
            this.converter = converter;
        }

        /// <summary>
        /// 发布Tick
        /// </summary>
        /// <param name="quotSource"></param>
        /// <param name="code"></param>
        /// <param name="tick"></param>
        /// <returns></returns>
        public bool AppendTick(string quotSource, string code, TTickInfo tick)
        {
            Contract.Requires(!string.IsNullOrEmpty(quotSource));
            Contract.Requires(!string.IsNullOrEmpty(code));
            Contract.Requires(tick != null);
            TTickInfoEntity tickInfoEntity = this.converter.Convert(tick);
            byte[] bytes = tickInfoEntity.StructToBytes<TTickInfoEntity>();
            return QuotationInfoChannel.UpdateTick(quotSource, code, bytes);
        }
        /// <summary>
        /// 获取单个商品的当日历史Tick
        /// </summary>
        /// <param name="quotSource"></param>
        /// <param name="code"></param>
        /// <param name="startIndex"></param>
        /// <param name="endIndex"></param>
        /// <returns></returns>
        public List<TTickInfo> GetTicks(string quotSource, string code, int? startIndex, int? endIndex)
        {
            Contract.Requires(!string.IsNullOrEmpty(quotSource));
            Contract.Requires(!string.IsNullOrEmpty(code));
            if (!startIndex.HasValue)
            {
                startIndex = 0;
            }
            if (!endIndex.HasValue)
            {
                endIndex = -1;
            }
            List<byte[]> tickBytesList = QuotationInfoChannel.GetTicks(quotSource, code, startIndex.Value, endIndex.Value);
            List<TTickInfo> rtn = new List<TTickInfo>();
            foreach (var bytes in tickBytesList)
            {
                TTickInfoEntity tickInfoEntity = StructHelper.BytesToStruct<TTickInfoEntity>(bytes);
                rtn.Add(this.converter.Convert(tickInfoEntity));
            }
            return rtn;
        }

    }
}
